﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TheOutfield.UmbExt.UniversalMediaPicker.Controls;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using umbraco.IO;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.SlideShare
{
    public class SlideShareCreateControl : AbstractCreateControl
    {
        private SlideShareService _service;

        private FileUpload fileFileUpload = new FileUpload();
        private TextBox titleTextBox = new TextBox();
        private TextBox descriptionTextBox = new TextBox();

        public SlideShareCreateControl(string config)
        {
            _service = new SlideShareService(config);
        }

        protected override void CreateChildControls()
        {
            fileFileUpload.ID = "fileFileUpload";
            titleTextBox.ID = "titleTextBox";
            descriptionTextBox.ID = "descriptionTextBox";

            fileFileUpload.CssClass = "guiInputText guiInputStandardSize";
            titleTextBox.CssClass = "guiInputText guiInputStandardSize";
            descriptionTextBox.CssClass = "guiInputText guiInputStandardSize";

            descriptionTextBox.TextMode = TextBoxMode.MultiLine;

            Controls.Add(fileFileUpload);
            Controls.Add(titleTextBox);
            Controls.Add(descriptionTextBox);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddFormRow("File:", fileFileUpload);
            writer.AddFormRow("Title:", titleTextBox);
            writer.AddFormRow("Description:", descriptionTextBox);
        }

        public override bool TrySave(out MediaItem savedMediaItem, out string message)
        {
            EnsureChildControls();

            if (fileFileUpload.HasFile)
            {
                try
                {
                    savedMediaItem = _service.CreateSlideshow(titleTextBox.Text,
                        descriptionTextBox.Text,
                        fileFileUpload.PostedFile).ToMediaItem();

                    message = "File created successfully";

                    return true;
                }
                catch (Exception e)
                {
                    savedMediaItem = null;
                    message = "An error occured creating the media item: " + e.Message;

                    return false;
                }
            }
            else
            {
                savedMediaItem = null;
                message = "No file selected";

                return false;
            }
        }
    }
}